package net.ib.mtalk.ui.attachment.geotag;

import java.io.IOException;
import java.util.List;

import net.ib.mtalk.R;
import net.ib.mtalk.ui.widget.MtalkProgressBar;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class GeotagActivity extends MapActivity implements LocationListener,OnClickListener{

	public static final String INTENT_GEOTAG_DATA = "geotag_data";
	
	private List<Overlay> mapOverlays;
	private Drawable drawble;
	private GeoOverlay overlays;
	private LocationManager locationMgr = null;
	private MapController mapControl;
	private GeoPoint p;
	private String searchable;
	private GeoPoint pointToSend;
	private GeoPoint currentPoint;
	private EditText editText;
	private MapView mapView;
	public static final String KEY_GEOPOINT = "Geo Point";
	public static final String KEY_CURRENT = "current only";
	private boolean sendMode = true;
	private Dialog loadingDialog;
	private boolean firstFind = true;
	private boolean firstResume = true;
	private String bestProvider;
	private String TAG2 = "com.android.settings";;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_geotag);
		
		Bundle bundle = getIntent().getExtras();
		mapView = (MapView) findViewById(R.id.map);
		mapView.setBuiltInZoomControls(true);

		Button sendButton = (Button) findViewById(R.id.geo_send);
		sendButton.setOnClickListener(this);

		Button cancelButton = (Button) findViewById(R.id.geo_cancel);
		cancelButton.setOnClickListener(this);
		
		ImageButton currentLocation = (ImageButton) findViewById(R.id.geo_current);
		currentLocation.setOnClickListener(this);
		
		mapOverlays = mapView.getOverlays();
		drawble = this.getResources().getDrawable(R.drawable.ic_location_pin);
		overlays = new GeoOverlay(drawble, this);
		
		editText = (EditText) findViewById(R.id.geo_search);
		ImageView searchButton = (ImageView) findViewById(R.id.geo_search_button);
		searchButton.setOnClickListener(this);

		mapControl = mapView.getController();
		
		toggleGpsState();
		
		locationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.NO_REQUIREMENT);

		bestProvider = locationMgr.getBestProvider(criteria, true);
				
		if (bundle != null && bundle.containsKey(KEY_GEOPOINT)) {
			sendMode = false;
			String coordinates = bundle.getString(KEY_GEOPOINT);
			String[] strArr = coordinates.split(",");
			pointToSend = new GeoPoint((int)(Double.parseDouble(strArr[0])*1E6), (int)(Double.parseDouble(strArr[1])*1E6));
			findViewById(R.id.geo_menu_bar).setVisibility(View.GONE);
			findViewById(R.id.searcdh_bar).setVisibility(View.GONE);
			OverlayItem overlayItem = new OverlayItem(pointToSend, "test", "Searched location");
			
//			overlays.deleteOverlay(overlayItem);
			overlays.addOverlay(overlayItem);
			mapOverlays.add(overlays);
			mapControl.animateTo(pointToSend);
			firstFind = false;
		}
		
		requestCurrentLocation();
		
//		firstFind = true;
	}
	
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	public void onLocationChanged(Location location) {
		
			toggleGpsState();
			if (sendMode) {
				double latitude = location.getLatitude();
				double longitude = location.getLongitude();
	
				GeoPoint newPoint = new GeoPoint((int) (latitude * 1E6),
						(int) (longitude * 1E6));
				pointToSend = newPoint;
				currentPoint = pointToSend;
			}
	
			mapControl.animateTo(pointToSend);
	
			mapControl.setZoom(16);
	
			OverlayItem overlaytItem = new OverlayItem(pointToSend, "test", "Current location");
			overlays.deleteOverlay(overlaytItem);
			overlays.addOverlay(overlaytItem);
	
			mapOverlays.add(overlays);
			
			loadingDialog.dismiss();
			
		
	}
	
	public void requestCurrentLocation(){
		if(sendMode){
			if (bestProvider != null) {
				locationMgr.requestLocationUpdates(bestProvider, 0, 0, GeotagActivity.this);
			} else {
				
				Builder alert = new AlertDialog.Builder(this)
						.setMessage(R.string.dialog_geo_warning)
						.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,	int which) {
										finish();
									}
								});
				alert.show();
			}
		}
		
		if(sendMode && firstResume && bestProvider != null){
			MtalkProgressBar progressBar = new MtalkProgressBar(this);
			loadingDialog = progressBar.onCreate(R.string.dialog_geo_loading);
			loadingDialog.show();
			Handler timer = new Handler();
			timer.postDelayed(new Runnable() {
				@Override
				public void run() {
					if(loadingDialog.isShowing()){
						loadingDialog.dismiss();
						timeoutHandler.sendMessage(timeoutHandler.obtainMessage());
					}
				}
			}, 15000);
			firstResume = false;
		}
	}
	
	public void searchPoint(String searchable) {
		Geocoder geocoder = new Geocoder(GeotagActivity.this);
		Message msg = new Message();
		
		try {
			List<Address> addresses = geocoder.getFromLocationName(searchable,	5);
			if (addresses.size() > 0) {
				p = new GeoPoint((int) (addresses.get(0).getLatitude() * 1E6),
						(int) (addresses.get(0).getLongitude() * 1E6));
				pointToSend = p;
				mapControl.animateTo(p);
				OverlayItem overlayItem = new OverlayItem(p, "test", "Searched location");

				overlays.deleteOverlay(overlayItem);
				overlays.addOverlay(overlayItem);
				mapOverlays.add(overlays);
			} else {
				Toast.makeText(this, R.string.no_geo_point,	Toast.LENGTH_LONG).show();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void selectPoint(GeoPoint point) {
		if(sendMode && point != null) {
			GeoPoint selectedPoint = point;
			pointToSend = point;
			mapControl.animateTo(point);
			mapControl.setZoom(16);

			OverlayItem overlayItem = new OverlayItem(selectedPoint, "test",
					"Current location");

			overlays.deleteOverlay(overlayItem);
			overlays.addOverlay(overlayItem);
			mapOverlays.add(overlays);
		}
	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	public void receivePoint(GeoPoint point) {
		mapControl.animateTo(point);
		mapControl.setZoom(16);

		OverlayItem overlayItem = new OverlayItem(point, "test",
				"Current location");

		overlays.addOverlay(overlayItem);
		mapOverlays.add(overlays);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.geo_search_button:
			if (editText != null && editText.getText() != null) {
				searchable = editText.getText().toString();
				searchPoint(searchable);
			}
			break;
		case R.id.geo_cancel:
			finish();
			break;
		case R.id.geo_send:
			Intent intent = new Intent();
			if(pointToSend != null) {
				intent.putExtra(INTENT_GEOTAG_DATA, pointToSend.getLatitudeE6()/1E6 + "," + pointToSend.getLongitudeE6()/1E6);
				setResult(RESULT_OK, intent);
				finish();
			}
			break;
		case R.id.geo_current:
			if(currentPoint != null){
				selectPoint(currentPoint);
			}else{
				System.out.println("@@");
				firstResume = true;
				requestCurrentLocation();
			}
			break;
		default:
			break;
		}
	}
	
	public final Handler timeoutHandler = new Handler() {
		public synchronized void handleMessage(Message msg) {
			Toast.makeText(GeotagActivity.this, getString(R.string.location_error), Toast.LENGTH_SHORT).show();
		}
	};
	
	private void toggleGpsState() {
		Intent intent = new Intent();
		intent.setClassName(TAG2, TAG2 + ".widget.SettingsAppWidgetProvider");
		intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
		intent.setData(Uri.parse(String.valueOf(3))); // ;)
		this.sendBroadcast(intent);
	}
}
